package org.feng.clog.config;

import org.feng.clog.annotation.WithoutLogin;
import org.feng.clog.utils.UserUtil;
import org.feng.clog.vo.UserVo;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器-获取登录用户信息并存储
 *
 * @author feng
 */
@Component
@Order(1)
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod action = (HandlerMethod) handler;

        // 使用了WithoutLogin，直接放行
        WithoutLogin withoutLogin = action.getMethodAnnotation(WithoutLogin.class);
        if(withoutLogin != null) {
            return true;
        }

        // 移除当前用户信息
        UserUtil.remove();

        // todo 获取请求中的信息
        // todo 校验当前登录用户

        // 获取用户信息-当前暂时用假数据
        UserVo userVo = new UserVo();
        userVo.setId(1001L);
        userVo.setPhone("18143431243");
        userVo.setUsername("feng123");
        UserUtil.set(userVo);

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();
    }
}
